package com.pt25.service.sys.interfaces.facade.inner;


import com.pt25.base.model.security.SecurityService;
import com.pt25.base.model.security.UserSession;
import com.pt25.base.model.security.aspect.LoginCheck;
import com.pt25.base.res.ResBody;
import com.pt25.service.sys.application.AdminApp;
import com.pt25.service.sys.interfaces.assembler.AdminAssembler;
import com.pt25.service.sys.interfaces.vo.admin.AdminLoginVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Tag(name = "login inner api")
@RestController
@RequestMapping("/inner-api/sys")
public class LoginInnerController {

    private final static String LOGIN = "/login";
    private final static String LOGOUT = "/logout";
    private final static String GET_USER_INFO = "/user-info";

    @Resource
    private AdminApp adminApp;

    @Resource
    private SecurityService securityService;

    @PostMapping(LOGIN)
    public ResBody login(@RequestBody @Valid AdminLoginVo adminLoginVO) {
        UserSession<?> userSession = adminApp.createSessionData(AdminAssembler.adminLoginVO2AdminUser(adminLoginVO));
        String token = securityService.login(userSession);
        Map<String, Object> returnData = new HashMap<>();
        returnData.put("token", token);
        return ResBody.builder().build().ok(returnData);
    }

    @LoginCheck
    @GetMapping(GET_USER_INFO)
    public ResBody getUserInfo() {
        UserSession<?> userSession = securityService.getSessionData();
        Map<String, Object> returnData = new HashMap<>();
        Set<String> roles = new HashSet<>();
        roles.addAll(userSession.getRoleList());
        roles.addAll(userSession.getPermissionList());
        returnData.put("roles", roles.toArray());
        returnData.put("name", adminApp.getAdminUser(Long.valueOf(userSession.getUid())).getAdmin());
        returnData.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        return ResBody.builder().build().ok(returnData);
    }


    @LoginCheck
    @GetMapping(LOGOUT)
    public ResBody logout() {
        securityService.logout();
        return ResBody.builder().build().ok();
    }
}
